/*
 * All rights Reserved, Designed By cloudland Copyright(C) 2010-2014
 *
 * fileName:  HttpHandle.java
 * author:  lei
 * Company:  Cloudland Studio
 * Createdate:  2013-9-14 下午8:55:07
 *   
 * Modification  History:
 *     Date           Author        Version        
 * -------------------------------------------
 * 2013-9-14          Lei            1.0        
 *
 * Why & What is modified:
 * 1.0: 文件创建
 */
package org.cloudland.web.context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 /**
 * <pre> 
 * TODO 请充分描述该类提供的作用, 或与其他类会有关联的使用。
 * 使用 java.lang.Object#toString(), 或者 {@link java.lang.Character Character} 等标签
 * </pre>
 * @ClassName  HttpHandle
 * @author  lei
 * @version  %I%, %G%
 * @see  
 * @since   JDK1.6
 *
 */
public class HttpHandle {
	
	/**
	 * handle 类对象实例
	 */
	private static HttpHandle handle = new HttpHandle();
	
	/**
	 * LOCAL_VARIABLE 本地变量
	 */
	private ThreadLocal<Entry> LOCAL_VARIABLE = new ThreadLocal<Entry>();
	
	/**
	 * <pre>
	 * 私有化构造函数，防止对象可手动实例化。
	 * </pre>
	 *   
	 */
	private HttpHandle() {}
	
	/**
	 * <pre>
	 * 获取 HttpHandle 实例对象。
	 * </pre>
	 *
	 * @return   
	 */
	public static HttpHandle getInstance() {
		return handle;
	}
	
	public static void doHttpSession(HttpServletRequest request, HttpServletResponse response) {
		handle.set(request, response);
	}
	
	/**
	 * <pre>
	 * HttpHandle 类对象是否可用。
	 * </pre>
	 *
	 * @return  true:表示可用
	 */
	public boolean isAvailable() {
		return LOCAL_VARIABLE.get() != null;
	}
	
	/**
	 * <pre>
	 * 返回当前请求对象。
	 * </pre>
	 *
	 * @return   
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest req = null;
		if (null != LOCAL_VARIABLE.get()) {
			req = LOCAL_VARIABLE.get().getRequest();
		}
		return req;
	}

	/**
	 * <pre>
	 * 返回当前响应对象。
	 * </pre>
	 *
	 * @return   
	 */
	public HttpServletResponse getResponse() {
		HttpServletResponse resp = null;
		if (null != LOCAL_VARIABLE.get()) {
			resp = LOCAL_VARIABLE.get().getResponse();
		}
		return resp;
	}
	
	/**
	 * <pre>
	 * 设置当前请求和响应对象。
	 * </pre>
	 *
	 * @param request
	 * @param response   
	 */
	private void set(HttpServletRequest request, HttpServletResponse response) {
		Entry entry = new Entry(request, response);
		LOCAL_VARIABLE.set(entry);
	}
	
	 /**
	 * <pre> 
	 * 保存当前线程使用的请求和响应对象。
	 * </pre>
	 * @ClassName  Entry
	 * @author  lei
	 * @version  %I%, %G%
	 * @see  
	 * @since   JDK1.6
	 *
	 */
	private static class Entry {

		HttpServletRequest request;

		HttpServletResponse response;

		Entry(HttpServletRequest request, HttpServletResponse response) {
			this.request = request;
			this.response = response;
		}
		
		private HttpServletRequest getRequest() {
			return this.request;
		}

		private HttpServletResponse getResponse() {
			return this.response;
		}
	}
	
}
